package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.UserInfo;
import cn.wolfcode.wolf2w.exception.LogincException;
import cn.wolfcode.wolf2w.redisService.IUserInfoRedisService;
import cn.wolfcode.wolf2w.repository.UserInfoRepository;
import cn.wolfcode.wolf2w.service.IUserInfoService;
import cn.wolfcode.wolf2w.util.AssertUtil;
import cn.wolfcode.wolf2w.util.Consts;
import cn.wolfcode.wolf2w.util.RedisKeys;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.UUID;

@Service
public class UserlnfoServiceImpl implements IUserInfoService {
    @Value("$(sms.url)")
    private String smsUrl;
    @Value("$(sms.appkey)")
    private String appkey;

    @Autowired
    private MongoTemplate template;

    @Autowired
    private UserInfoRepository repository;
    @Autowired
    private IUserInfoRedisService userInfoRedisService;

    @Override
    public void save(UserInfo userInfo) {
        userInfo.setId(null);
        repository.save(userInfo);
    }

    @Override
    public void update(UserInfo userInfo) {
        repository.save(userInfo);
    }

    @Override
    public void delete(String id) {
        repository.deleteById(id);
    }

    @Override
    public UserInfo get(String id) {
        UserInfo userInfo =repository.findById(id).orElse(null);
        return userInfo;
    }

    @Override
    public List<UserInfo> list() {
        return repository.findAll();
    }

    @Override
    public boolean checkPhone(String phone) {
        UserInfo userInfo = repository.findByPhone(phone);
        return userInfo!=null;
    }

    @Override
    public void sendVerifyCode(String phone) {
       boolean b =  userInfoRedisService.isNull(RedisKeys.USER_LOGCOENT);
       if (!b){
           //addCode设置次数
           userInfoRedisService.addCode(RedisKeys.USER_LOGCOENT);
       }


        //1:创建短信验证码
        String code = UUID.randomUUID().toString()
                .replaceAll("-", "").substring(0, 4);
        //2:拼接一个短信
        StringBuilder sb = new StringBuilder(80);
        sb.append("您好, 您的注册验证码是:").append(code).append("请在").append(Consts.VERIFY_CODE_VAI_TIME)
                .append("分钟之内使用");
        userInfoRedisService.subtract();
        //3:发送短信 : 假装发一个短信
        System.out.println(sb.toString());
        userInfoRedisService.setVerifyCode(phone,code);

        //Url:https://way.jd.com/chuangxin/dxjk?mobile=13568813957&content=【创信】你的验证码是：5873，3分钟内有效！&appkey=61ff4188d8edf3b42dcacbc9be115057
        /*String url = "https://way.jd.com/chuangxin/dxjk?" +
                "mobile="+phone+"&content=【叩丁狼狼】" +
                sb.toString()+ "&" +
                "appkey=61ff4188d8edf3b42dcacbc9be115057";
        //请求的发送类
        RestTemplate restTemplate = new RestTemplate();
        sms.url=https://way.jd.com/chuangxin/dxjk?mobile={1}&content={2}&sendTime=&appkey={3}
        sms.appkey=61ff4188d8edf3b42dcacbc9be115057
        Map map = restTemplate.getForObject(smsUrl, Map.class,phone, sb.toString(), appkey );
        //getForObject 随便返回个obj回来
        String ret = restTemplate.getForObject(url,String.class);
        System.out.println(ret);
        //没有success就是不成功
        if(!ret.contains("Success")){
            throw  new LogincException("短信发送失败");
        }*/

        userInfoRedisService.setVerifyCode(phone, code);
    }

    @Override
    public void rehist(String phone, String nickname, String password, String rpassword, String verifyCode) {
        //判断是否手机号是否存在
        //首先手机号不能为空
        AssertUtil.isNull(phone,"手机号不能为空");
        AssertUtil.isNull(nickname,"昵称不能为空");
        AssertUtil.isNull(password,"密码不能为空");
        AssertUtil.isNull(rpassword,"密码不能为空");
        AssertUtil.isNull(verifyCode,"验证码不能为空");
        //判断2次输入的密码是否一致
        AssertUtil.isEquals(password, rpassword, "两次输入密码不一致");
        //判断手机号是否符合格式
        AssertUtil.isMobileNO(phone);
        //判断手机号是否唯一
        if (this.checkPhone(phone)) {
            throw new LogincException("手机号已被注册");
        }
        //判断验证是否正确
        String code =  userInfoRedisService.getVerifyCode(phone);
        System.out.println(code);
        //判断验证码是否有效 equalsIgnoreCase忽略大小写的比较
        if(code==null || !code.equalsIgnoreCase(verifyCode)){
            throw new LogincException("验证码错误或失效");
        }
        //注册
        UserInfo userInfo = new UserInfo();
        userInfo.setPhone(phone);
        userInfo.setNickname(nickname);
        userInfo.setEmail("");
        userInfo.setPassword(password);
        userInfo.setGender(UserInfo.GENDER_SECRET);
        userInfo.setLevel(userInfo.getLevel());
        userInfo.setCity("");
        userInfo.setHeadImgUrl(("/images/12.jpg"));
        userInfo.setState(UserInfo.STATE_NORMAL);
        userInfo.setId(null);

        //throw new RuntimeException("恶心weqweqweqweqweqweqweqweqweqweqwe");
        repository.save(userInfo);



    }

    @Override
    public UserInfo userLogin(String username, String password) {
        AssertUtil.isNull(username,"账户不能为空");
        AssertUtil.isNull(password,"密码不能为空");
        UserInfo byPhone = repository.findByPhone(username);
        if (byPhone==null){
            throw new LogincException("账号不存在");
        }
        if(!password.equals(byPhone.getPassword())){
            throw  new LogincException("密码错误");
        }
        return byPhone;
    }

    @Override
    public List<UserInfo> queryByCity(String keyword) {
        List<UserInfo> infos = repository.findByCity(keyword);
        return infos;
    }


}
